package com.kcwl.carrier.application.service;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.kcwl.carrier.domain.condition.HistoryRemark;
import com.kcwl.carrier.domain.entity.*;
import com.kcwl.carrier.domain.service.*;
import com.kcwl.carrier.infrastructure.enums.AuditAuthenticationStatusEnum;
import com.kcwl.carrier.infrastructure.enums.CarrierUseErrorCodeEnum;
import com.kcwl.carrier.infrastructure.enums.VehicleTrailerRemarkEnum;
import com.kcwl.carrier.infrastructure.exceptions.CarrierUserException;
import com.kcwl.carrier.infrastructure.repository.po.VehicleTrailerPO;
import com.kcwl.carrier.infrastructure.utils.StringUtil;
import com.kcwl.carrier.interfaces.command.VehicleTrailerCommand;
import com.kcwl.carrier.interfaces.dto.VehicleBatchAuditDTO;
import com.kcwl.carrier.interfaces.dto.VehicleTrailerInfoDTO;
import com.kcwl.carrier.interfaces.dto.VehicleTrailerListDTO;
import com.kcwl.carrier.interfaces.enums.VehicleInfoEnums;
import com.kcwl.carrier.interfaces.query.IdQuery;
import com.kcwl.carrier.interfaces.query.PlateNumberQuery;
import com.kcwl.carrier.interfaces.query.VehicleTrailerQuery;
import com.kcwl.ddd.application.constants.YesNoEnum;
import com.kcwl.ddd.infrastructure.api.ResponseMessage;
import com.kcwl.ddd.interfaces.dto.ListResultDTO;
import com.kcwl.ddd.interfaces.dto.PageInfoDTO;
import com.kcwl.file.interfaces.api.IFileRemoteService;
import com.kcwl.file.interfaces.dto.FileUrlDTO;
import com.kcwl.file.interfaces.query.FileUrlQuery;
import com.kcwl.framework.utils.KcBeanConverter;
import com.kcwl.mdm.interfaces.api.IVehicleTypeService;
import com.kcwl.mdm.interfaces.dto.VehicleTypeDTO;
import com.kcwl.mdm.interfaces.query.VehicleTypeDetailQuery;
import com.kcwl.mdm.interfaces.query.VehicleTypeQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.kcwl.carrier.infrastructure.constant.TrailerConstant.*;

/**
 * @描述 添加挂车
 * @创建人 zhl
 * @创建时间 2022/11/3
 * @修改人和其它信息
 */
@Service
@Slf4j
public class TrailerApplicationService {

    @Autowired
    private VehicleTrailerDomainService vehicleTrailerDomainService;
    @Autowired
    private VehicleInfoDomainService vehicleInfoDomainService;
    @Autowired
    private AuditRejectReasonDomainService auditRejectReasonDomainService;
    @Autowired
    private IFileRemoteService fileRemoteService;
    @Autowired
    private IVehicleTypeService vehicleTypeService;
    @Autowired
    private CarrierMappingDomainService mappingDomainService;
    @Autowired
    private CarrierInfoDomainService carrierInfoDomainService;
    @Resource
    private Gson gson;


    /**
     * @描述 添加挂车
     * @参数 [trailerCommand]
     * @返回值 java.lang.Long
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    public Long addTrailer(VehicleTrailerCommand trailerCommand) {
        VehicleTrailerInfo trailer = KcBeanConverter.toBean(trailerCommand, VehicleTrailerInfo.class);
        Long trailerId = this.addTrailer(trailer, null != trailerCommand.getVehicleId() ? trailerCommand.getVehicleId() : 0L, SOURCE_SUPPLY);
        return trailerId;
    }

    /**
     * @描述 添加挂车信息
     * @参数 [vehicleTrailer, vehicleId, source]
     * @返回值 void
     * @创建人 zhl
     * @创建时间 2022/11/1
     * @修改人和其它信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Long addTrailer(VehicleTrailerInfo trailer, Long vehicleId, int source) {
        // 设置参数
        Date date = new Date();
        if (ObjectUtil.isEmpty(trailer.getAuthenticationStatus())) {
            trailer.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.UNVERIFIED.getCode());
            trailer.setSubmitTime(date);
            trailer.setCreateTime(date);
            trailer.setUpdateTime(date);
        } else {
            trailer.setAuthenticationTime(date);
        }
        trailer.setIsDel(YesNoEnum.NAY.getValue());
        trailer.setSource(source);
        if (!StringUtil.checkPlateNum(trailer.getPlateNumber())) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.PLATENUMBER_FORMAT_ERROR);
        }
        Long trailerId = checkTrailerExist(trailer.getPlateNumber(), trailer.getCarrierId());
        if (trailerId > 0 && SOURCE_SUPPLY.equals(source) && VEHICLE_EMPTY.equals(vehicleId)) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.TRAILER_REPEATED_ADD);
        }

        // 添加挂车
        if (trailerId == 0) {
            VehicleTrailerPO trailerPO = KcBeanConverter.toBean(trailer, VehicleTrailerPO.class);
            vehicleTrailerDomainService.save(trailerPO);
            trailerId = trailerPO.getId();
        }

        // 新加挂车需要与车辆关联
        if (null != vehicleId && vehicleId > 0) {//需要绑定车辆
            if (checkTrailerBind(trailerId, trailer.getCarrierId())) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.TRAILER_REPEATED_RELATION);
            }
            updateVehicleInfo(vehicleId, trailerId);

            // 存在挂车更新挂车
            if (SOURCE_INIT.equals(source)) {
                updateVehicleTrailer(trailerId);
            }
        }
        return trailerId;
    }

    /**
     * 检测挂车存在
     *
     * @param plateNumber
     * @param carrierId
     * @return
     */
    private Long checkTrailerExist(String plateNumber, Long carrierId) {
        VehicleTrailerCondition condition = new VehicleTrailerCondition();
        condition.setPlateNumber(plateNumber);
        condition.setCarrierId(carrierId);
        condition.setIsDel(0);
        List<VehicleTrailerInfo> trailers = vehicleTrailerDomainService.getList(condition);
        return (null == trailers || trailers.isEmpty()) ? 0 : trailers.get(0).getId();
    }

    /**
     * 检测挂车是否被挂载
     *
     * @param trailerId
     * @return
     */
    private boolean checkTrailerBind(Long trailerId, Long carrierId) {
        Map<String, Object> params = new HashMap<>();
        params.put("trailerId", trailerId);
        params.put("carrierId", carrierId);
        return vehicleInfoDomainService.countTrailerBindNum(params);
    }

    /**
     * 更新车辆的挂车信息
     *
     * @param vehicleId
     * @param trailerId
     */
    private void updateVehicleInfo(Long vehicleId, Long trailerId) {
        VehicleInfo vehicle = new VehicleInfo();
        vehicle.setId(vehicleId);
        vehicle.setTrailerId(trailerId);
        vehicleInfoDomainService.updateVehicle(vehicle);
    }

    /**
     * 更新审核状态和来源
     *
     * @param trailerId
     */
    void updateVehicleTrailer(Long trailerId) {
        VehicleTrailerInfo vehicleTrailer = new VehicleTrailerInfo();
        Date date = new Date();
        vehicleTrailer.setId(trailerId);
        vehicleTrailer.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.UNVERIFIED.getCode());
        vehicleTrailer.setSubmitTime(date);
        vehicleTrailer.setSource(SOURCE_INIT);
        vehicleTrailer.setUpdateTime(date);
        vehicleTrailerDomainService.updateById(vehicleTrailer);
    }

    /**
     * @描述 更新挂车信息
     * @参数 [trailer, trailerId]
     * @返回值 void
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    private void updateVehicleTrailer(VehicleTrailerInfo trailer, Long trailerId) {
        VehicleTrailerInfo vehicleTrailerInfo = vehicleTrailerDomainService.getById(trailerId);
        if (vehicleTrailerInfo.getAuthenticationStatus() == VehicleInfoEnums.AuthenticationStatusEnum.VERIFIED_FAIL.getCode()) {
            trailer.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.UNVERIFIED.getCode());
        }
        trailer.setId(trailerId);
        trailer.setUpdateTime(new Date());
        trailer.setSource(SOURCE_INIT);
        vehicleTrailerDomainService.updateById(trailer);
    }

    /**
     * 修改(跟随牵引车一同修改)
     *
     * @param trailer
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(VehicleTrailerInfo trailer, Long vehicleId) {
        if (!StringUtil.checkPlateNum(trailer.getPlateNumber())) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.PLATENUMBER_FORMAT_ERROR);
        }
        //修改后的车牌+当前车主校验是否已经存在挂车
        Long trailerId = checkTrailerExist(trailer.getPlateNumber(), trailer.getCarrierId());
        if (trailerId == BigInteger.ZERO.longValue()) {
            //新增挂车并修改车辆表中挂车id为新增后的
            trailer.setId(null);
            addTrailer(trailer, vehicleId, 1);
        } else {
            //修改后的挂车id跟原车辆记录中的挂车id不一致
            if (!trailerId.equals(trailer.getId())) {
                //校验挂车是否被其他车辆绑定
                if (checkTrailerOtherBind(trailerId, trailer.getCarrierId(), vehicleId)) {
                    throw new CarrierUserException(CarrierUseErrorCodeEnum.TRAILER_REPEATED_RELATION);
                }
                //修改车辆表中挂车id
                updateVehicleInfo(vehicleId, trailerId);
            }
            updateVehicleTrailer(trailer, trailerId);
        }
    }

    /**
     * @描述 检查挂车是否被其他挂车绑定
     * @参数 [trailerId, carrierId, id]
     * @返回值 boolean
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    private boolean checkTrailerOtherBind(Long trailerId, Long carrierId, Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("trailerId", trailerId);
        params.put("carrierId", carrierId);
        params.put("id", id);
        return vehicleInfoDomainService.countTrailerBindNum(params);
    }

    /**
     * @描述 删除挂车
     * @参数 [trailerId]
     * @返回值 java.lang.Boolean
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    public Boolean delTrailer(Long trailerId) {
        VehicleTrailerInfo trailerInfo = vehicleTrailerDomainService.getById(trailerId);

        //校验挂车是否被绑定，若被绑定，不允许删除
        if (ObjectUtil.isNotEmpty(trailerInfo) && !checkTrailerBind(trailerId, trailerInfo.getCarrierId())) {
            trailerInfo.setIsDel(YesNoEnum.YEA.getValue());

            // 删除挂车
            vehicleTrailerDomainService.updateById(trailerInfo);

            // 删除绑定
            vehicleInfoDomainService.delTrailerBind(trailerId);
        } else {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.TRAILER_NOT_ALLOWED_DELETE);
        }
        return Boolean.TRUE;
    }

    /**
     * @描述 更新挂车
     * @参数 [command]
     * @返回值 java.lang.Boolean
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    public Boolean updateTrailer(VehicleTrailerCommand command) {
        VehicleTrailerInfo vehicleTrailerInfo = KcBeanConverter.toBean(command, VehicleTrailerInfo.class);
        Date date = new Date();
        vehicleTrailerInfo.setId(command.getTrailerId());
        vehicleTrailerInfo.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.UNVERIFIED.getCode());
        vehicleTrailerInfo.setUpdateTime(date);
        vehicleTrailerInfo.setSubmitTime(date);
        vehicleTrailerDomainService.updateTrailer(vehicleTrailerInfo);
        return Boolean.TRUE;
    }

    /**
     * @描述 挂车列表
     * @参数 [query]
     * @返回值 com.kcwl.ddd.interfaces.dto.PageInfoDTO<com.kcwl.carrier.interfaces.dto.VehicleTrailerInfoDTO>
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    public PageInfoDTO<VehicleTrailerInfoDTO> getTrailerList(PlateNumberQuery query) {
        PageInfoDTO<VehicleTrailerInfoDTO> pageInfoDTO = vehicleTrailerDomainService.getTrailerList(query);
        List<VehicleTrailerInfoDTO> infoDTOList = pageInfoDTO.getList();
        if (infoDTOList.size() > 0) {
            // 查询车辆类型列表
            List<Long> typeList = infoDTOList.stream().map(VehicleTrailerInfoDTO::getVehicleType).filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
            if (!typeList.isEmpty()) {
                Map<Long, VehicleTypeDTO> vehicleTypeMap = getVehicleType(typeList);

                // 设置车型名称
                infoDTOList.forEach(vehicleTrailerInfoDTO -> {
                    if (ObjectUtil.isNotEmpty(vehicleTrailerInfoDTO.getVehicleType())) {
                        VehicleTypeDTO vehicleTypeDTO = vehicleTypeMap.get(vehicleTrailerInfoDTO.getVehicleType());
                        if (ObjectUtil.isNotEmpty(vehicleTypeDTO)) {
                            vehicleTrailerInfoDTO.setVehicleTypeName(vehicleTypeDTO.getVehicleTypeName());
                        }
                    }
                });
            }
        }
        pageInfoDTO.setList(infoDTOList);

        return pageInfoDTO;
    }

    /**
     * @描述 获取车型
     * @参数 [typeList]
     * @返回值 java.util.Map<java.lang.Long, com.kcwl.mdm.interfaces.dto.VehicleTypeDTO>
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    private Map<Long, VehicleTypeDTO> getVehicleType(List<Long> typeList) {
        if (typeList.size() > 0) {
            ResponseMessage<ListResultDTO<VehicleTypeDTO>> responseMessage = vehicleTypeService.queryVehicleType(new VehicleTypeQuery(typeList));
            if (responseMessage.isSuccess()) {
                List<VehicleTypeDTO> dtoList = responseMessage.getResult().getList();
                Map<Long, VehicleTypeDTO> vehicleTypeMap = dtoList.stream().collect(Collectors.toMap(VehicleTypeDTO::getVehicleType, Function.identity()));
                return vehicleTypeMap;
            }
        }
        return new HashMap<>();
    }

    /**
     * 处理驳回原因
     *
     * @param dto
     */
    private void setRejectReasons(VehicleTrailerInfoDTO dto) {
        String reason = dto.getAuthenticationRemarkType();
        if (!com.kcwl.framework.utils.StringUtil.isEmpty(reason)) {
            dto.setRejectReason(reason);
            if (!com.kcwl.framework.utils.StringUtil.isEmpty(reason)) {
                List<Long> ids = Arrays.asList(reason.split(",")).parallelStream().map(a -> Long.parseLong(a.trim())).collect(Collectors.toList());

                //调用驳回原因接口
                List<AuditRejectReasonInfo> auditRejectReasons = auditRejectReasonDomainService.selectIds(ids);
                List<String> rejectReasons = new ArrayList<>();
                auditRejectReasons.forEach(a -> {
                    rejectReasons.add(a.getGroupName() + a.getReason());
                });
                dto.setRejectReasonList(rejectReasons);
            }
        }
    }

    /**
     * @描述 挂车详情
     * @参数 [query]
     * @返回值 com.kcwl.carrier.interfaces.dto.VehicleTrailerInfoDTO
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    public VehicleTrailerInfoDTO getTrailerDetail(IdQuery query) {
        // 查询挂车详情
        VehicleTrailerInfoDTO dto = KcBeanConverter.toBean(vehicleTrailerDomainService.getTrailerDetail(query.getId()), VehicleTrailerInfoDTO.class);

        // 查询车辆信息
        VehicleInfo vehicleInfo = vehicleInfoDomainService.queryByTrailerId(dto.getId(), dto.getCarrierId());
        dto.setVehicleId(vehicleInfo.getId());
        dto.setVehiclePlateNumber(vehicleInfo.getPlateNumber());
        dto.setVehicleType(vehicleInfo.getVehicleType());
        dto.setLoads(vehicleInfo.getLoads());

        // 查询mapping信息
        CarrierMappingInfo mappingInfo = mappingDomainService.getDriverByVehicleId(vehicleInfo.getId(), vehicleInfo.getCarrierId());
        dto.setDriverId(mappingInfo.getDriverId());

        // 查询司机信息
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(mappingInfo.getDriverId());
        dto.setDriverName(carrierInfo.getName());

        // 查询车型
        ResponseMessage<VehicleTypeDTO> responseMessage = vehicleTypeService.queryVehicleTypeDetail(new VehicleTypeDetailQuery(dto.getVehicleType()));
        VehicleTypeDTO vehicleTypeDTO = responseMessage.getResult();
        dto.setVehicleTypeName(vehicleTypeDTO.getVehicleTypeName());

        // 处理驳回原因
        setRejectReasons(dto);

        return dto;
    }

    /**
     * @描述 获取挂车列表分页
     * @参数 [query]
     * @返回值 com.kcwl.ddd.interfaces.dto.PageInfoDTO<com.kcwl.carrier.interfaces.dto.VehicleTrailerListDTO>
     * @创建人 zhl
     * @创建时间 2023/1/16
     * @修改人和其它信息
     */
    @Transactional(rollbackFor = Exception.class)
    public PageInfoDTO<VehicleTrailerListDTO> queryVehicleTrailerPage(VehicleTrailerQuery query) {
        //车辆来源为补录
        query.setSource(2);
        query.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.UNVERIFIED.getCode());
        PageInfoDTO<VehicleTrailerListDTO> vehicleTrailerListDTO = vehicleTrailerDomainService.queryVehicleTrailerPage(query);
        if (vehicleTrailerListDTO != null && !vehicleTrailerListDTO.getList().isEmpty()) {
            List<VehicleTrailerListDTO> dtoList = vehicleTrailerListDTO.getList();
            ObjectMapper mapper = new ObjectMapper();
            //将远程图片一次性下载下来放在map
            List<String> trailerPics = dtoList.stream().map(VehicleTrailerListDTO::getTransportationFrontPic).collect(Collectors.toList());
            Map<String, String> pairUrl = new HashMap<>();
            if (!trailerPics.isEmpty()) {
                FileUrlQuery fileUrlQuery = new FileUrlQuery();
                fileUrlQuery.setKeys(trailerPics);
                ResponseMessage<List<FileUrlDTO>> urlByKeys = fileRemoteService.getUrlByKeys(fileUrlQuery);
                urlByKeys.getResult().forEach(fileUrlVo -> {
                    pairUrl.put(fileUrlVo.getKey(), fileUrlVo.getUrl());
                });
            }
            //修正为上传地址
            dtoList.forEach(vo -> {
                try {
                    List<VehicleTrailerListDTO.HistoryRemarks> historyRemarks = new ArrayList<>();
                    String historyRemark = vo.getHistoryRemark();
                    //加工历史备注为列表信息
                    if (historyRemark != null && !StringUtils.isEmpty(historyRemark)) {
                        VehicleTrailerListDTO.HistoryRemarks history = mapper.readValue(historyRemark, VehicleTrailerListDTO.HistoryRemarks.class);
                        String historyRemarksRemark = history.getRemark();
                        String historyRemarksUpdateTime = history.getUpdateTime();
                        String[] splitHistoryRemarksRemark = historyRemarksRemark.split("@");
                        String[] splitHistoryRemarksUpdateTime = historyRemarksUpdateTime.split("@");
                        for (int i = 0; i < splitHistoryRemarksRemark.length; i++) {
                            String splitRemark = splitHistoryRemarksRemark[i];
                            String splitUpdateTime = splitHistoryRemarksUpdateTime[i];
                            historyRemarks.add(new VehicleTrailerListDTO.HistoryRemarks(splitRemark, splitUpdateTime));
                        }
                        vo.setHistoryRemarks(historyRemarks);
                    }
                    String trailerTransportationFrontPic = vo.getTransportationFrontPic();
                    if (StringUtils.isNotBlank(trailerTransportationFrontPic)) {
                        vo.setTransportationFrontPicUrl(pairUrl.get(trailerTransportationFrontPic));
                    }
                } catch (IOException e) {
                    throw new CarrierUserException(CarrierUseErrorCodeEnum.TRAILER_LIST_ERROR);
                }
            });
        }
        return vehicleTrailerListDTO;
    }

    public Boolean auditVehicleTrailerDetail(VehicleTrailerCommand command) {
        log.error("挂车审核通过的参数为：command=", command.toString());
        getVehicleTrailerToUpdate(command);
        VehicleTrailerInfo vehicleTrailerInfo = KcBeanConverter.toBean(command, VehicleTrailerInfo.class);
        vehicleTrailerInfo.setId(command.getTrailerId());
        vehicleTrailerInfo.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.VERIFIED.getCode());
        Date date = new Date();
        vehicleTrailerInfo.setUpdateTime(date);
        vehicleTrailerInfo.setAuthenticationTime(date);
        vehicleTrailerDomainService.updateTrailer(vehicleTrailerInfo);
        return Boolean.TRUE;
    }

    public void getVehicleTrailerToUpdate(VehicleTrailerCommand command) {
        String plateNumber = command.getPlateNumber();
        Long carrierId = command.getCarrierId();
        //获取修改的挂车id
        Long id = command.getTrailerId();
        VehicleTrailerCondition condition = new VehicleTrailerCondition();
        condition.setPlateNumber(plateNumber);
        condition.setCarrierId(carrierId);
        condition.setIsDel(YesNoEnum.NAY.getValue());
        //查找车牌号司机存在的挂车(待审核状态下的）
        // 1.存在多个直接报错，2.存在且如果与本次挂车id不一致，则也报错
        List<VehicleTrailerInfo> list = vehicleTrailerDomainService.getList(condition);
        int size = list.size();
        if (size > 0) {
            if (size > 1) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.TRAILER_REPEATED_ADD);
            }
            VehicleTrailerInfo exist = list.get(0);
            @NotNull Long existId = exist.getId();
            if (existId.longValue() != id.longValue()) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.TRAILER_REPEATED_ADD);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean rejectVehicleTrailerDetail(VehicleTrailerCommand command) {
        //设置最大的历史评论字符长度
        int maxLength = 10000;
        //1.获取挂车id
        Date now = new Date();
        Long id = command.getTrailerId();
        VehicleTrailerInfo vehicleTrailer = new VehicleTrailerInfo();
        vehicleTrailer.setId(id);
        String authenticationRemarkType = command.getAuthenticationRemarkType();
        //2.获取驳回类型串authentication_remark_type，并根据驳回类型拼接驳回原因authentication_remark，
        String authenticationRemark = null;
        if (authenticationRemarkType != null) {
            StringBuilder remarkBuilder = new StringBuilder();
            String[] remarkTypes = authenticationRemarkType.split(",");
            for (String remarkType : remarkTypes) {
                remarkBuilder.append(VehicleTrailerRemarkEnum.getTypeByValue(Integer.parseInt(remarkType)).getValue());
                remarkBuilder.append(",");
            }
            String remarkBuilderStr = remarkBuilder.toString();
            authenticationRemark = remarkBuilderStr.substring(0, remarkBuilderStr.length() - 1);
            vehicleTrailer.setAuthenticationRemark(authenticationRemark);
            vehicleTrailer.setAuthenticationRemarkType(authenticationRemarkType);
            VehicleTrailerInfo trailerDetail = vehicleTrailerDomainService.getById(id);
            String historyRemark = trailerDetail.getHistoryRemark();
            String updateTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            //3.以@连接追加到历史备注记录
            ObjectMapper mapper = new ObjectMapper();
            try {
                // 如果历史评论不为空，则需要校验长度，超过一万自动清空
                if (historyRemark != null && !historyRemark.trim().isEmpty()) {
                    HistoryRemark remarkNew = new HistoryRemark();
                    HistoryRemark remark = mapper.readValue(historyRemark, HistoryRemark.class);
                    remarkNew.setRemark(remark.getRemark() + "@" + authenticationRemark);
                    remarkNew.setUpdateTime(remark.getUpdateTime() + "@" + updateTimeStr);
                    String historyRemarkNew = mapper.writeValueAsString(remarkNew);
                    if (historyRemarkNew.length() > maxLength) {
                        HistoryRemark curRemark = new HistoryRemark();
                        curRemark.setUpdateTime(updateTimeStr);
                        curRemark.setRemark(authenticationRemark);
                        log.warn("===========historyRemark not empty===========Vehicle_history_length:" + historyRemarkNew.length());
                        vehicleTrailer.setHistoryRemark(mapper.writeValueAsString(curRemark));
                    } else {
                        vehicleTrailer.setHistoryRemark(historyRemarkNew);
                    }
                } else {
                    HistoryRemark remark = new HistoryRemark();
                    remark.setRemark(authenticationRemark);
                    remark.setUpdateTime(updateTimeStr);
                    vehicleTrailer.setHistoryRemark(mapper.writeValueAsString(remark));
                }
            } catch (IOException e) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.HISTORY_REMARK_ERROR);
            }
        }
        vehicleTrailer.setUpdateTime(now);
        vehicleTrailer.setAuthenticationTime(now);
        vehicleTrailer.setAuthenticationStatus(VehicleInfoEnums.AuthenticationStatusEnum.VERIFIED_FAIL.getCode());
        vehicleTrailerDomainService.updateById(vehicleTrailer);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public VehicleBatchAuditDTO batchAuditVehicleTrailer(List<VehicleTrailerCommand> conditions) {
        AtomicInteger successCount = new AtomicInteger();
        AtomicInteger rejectCount = new AtomicInteger();
        conditions.forEach(condition -> {
            Integer status = condition.getAuthenticationStatus();
            if (AuditAuthenticationStatusEnum.SUCCESS.getCode() != status) {
                //走驳回逻辑
                rejectVehicleTrailerDetail(condition);
                rejectCount.getAndIncrement();
            } else {
                //走审核通过逻辑
                auditVehicleTrailerDetail(condition);
                successCount.getAndIncrement();
            }
        });
        return new VehicleBatchAuditDTO(successCount.intValue(), rejectCount.intValue(), "");
    }
}
